package crontab

import (
	"fmt"
	global2 "longmen/server/config/global"
	"longmen/server/internal/services/nami/utils"
	"longmen/server/pkg/db/mysql/models/models_guess"
	"longmen/server/pkg/db/mysql/models/models_main"
	"time"
)

func SyncTopUser() {
	syncWeekGuessStat()
	syncDayStat()
	syncWeekStat()
	syncMonthStat()
	FixFansStat()
}

type Stat struct {
	Stat int64
	UID  int64
}

func syncDayStat() {
	today := time.Now().Format("2006-01-02")
	//select CURDATE() 当前  如果web 与数据库时间不同步，可改为使用数据库本地时间
	//select date_sub(curdate(),INTERVAL WEEKDAY(CURDATE()) DAY) 本周第一天
	//SELECT str_to_date(concat(date_format(curdate(),'%Y-%m-'),'01'), '%Y-%m-%d') 当月第一天
	// 粉丝
	exec := global2.Live().Exec("INSERT INTO db_top_user (uid,updated_at,date,day_fans_stat) select anchorid as uid,now(),date_format(now(),'%Y-%m-%d') ,"+
		"count(1) as stat from db_anchor_fans where create_time>=? group by anchorid order by stat desc limit 20  ON DUPLICATE KEY UPDATE day_fans_stat=values(day_fans_stat)", today)
	global2.Log.Debug(fmt.Sprintf("日期为:%s ,更新当日粉丝数为%d条", today, exec.RowsAffected))
	// 贡献
	exec = global2.Live().Exec("INSERT INTO db_top_user (uid,updated_at,date,day_diamond_stat) select  uid,now(),date_format(now(),'%Y-%m-%d') ,"+
		"sum(actual_spend)/10 as stat from db_gift_log where create_time>=? and spend_type=2 group by uid order by stat desc limit 20 ON DUPLICATE KEY UPDATE day_diamond_stat=values(day_diamond_stat)", today)
	global2.Log.Debug(fmt.Sprintf("日期为:%s ,更新当日贡献数为%d条", today, exec.RowsAffected))

}

func syncWeekStat() {
	// 粉丝
	exec := global2.Live().Exec("INSERT INTO db_top_user (uid,updated_at,date,week_fans_stat) select anchorid as uid,now(),date_format(now(),'%Y-%m-%d') ,"+
		"count(1) as stat from db_anchor_fans where create_time>=? group by anchorid order by stat desc limit 20  ON DUPLICATE KEY UPDATE week_fans_stat=values(week_fans_stat)", utils.WeekStart().Format("2006-01-02"))
	global2.Log.Debug(fmt.Sprintf("日期为:%s ,更新当周粉丝数为%d条", utils.WeekStart().Format("2006-01-02"), exec.RowsAffected))
	// 贡献
	exec = global2.Live().Exec("INSERT INTO db_top_user (uid,updated_at,date,week_diamond_stat) select  uid,now(),date_format(now(),'%Y-%m-%d') ,"+
		"sum(actual_spend)/10 as stat from db_gift_log where create_time>=? and spend_type=2 group by uid order by stat desc limit 20 ON DUPLICATE KEY UPDATE week_diamond_stat=values(week_diamond_stat)", utils.WeekStart().Format("2006-01-02"))
	global2.Log.Debug(fmt.Sprintf("日期为:%s ,更新当周贡献数为%d条", utils.WeekStart().Format("2006-01-02"), exec.RowsAffected))

}

func syncMonthStat() {
	// 粉丝
	exec := global2.Live().Exec("INSERT INTO db_top_user (uid,updated_at,date,month_fans_stat) select anchorid as uid,now(),date_format(now(),'%Y-%m-%d') ,"+
		"count(1) as stat from db_anchor_fans where create_time>=? group by anchorid order by stat desc limit 20  ON DUPLICATE KEY UPDATE month_fans_stat=values(month_fans_stat)", utils.MonthStart().Format("2006-01-02"))
	global2.Log.Debug(fmt.Sprintf("日期为:%s ,更新当月粉丝数为%d条", utils.MonthStart().Format("2006-01-02"), exec.RowsAffected))
	// 贡献
	exec = global2.Live().Exec("INSERT INTO db_top_user (uid,updated_at,date,month_diamond_stat) select  uid,now(),date_format(now(),'%Y-%m-%d') ,"+
		"sum(actual_spend)/10 as stat from db_gift_log where create_time>=? and spend_type=2 group by uid order by stat desc limit 20 ON DUPLICATE KEY UPDATE month_diamond_stat=values(month_diamond_stat)", utils.MonthStart().Format("2006-01-02"))
	global2.Log.Debug(fmt.Sprintf("日期为:%s ,更新当月贡献数为%d条", utils.MonthStart().Format("2006-01-02"), exec.RowsAffected))
}

// 同步取消关注的数值
func FixFansStat() {
	today := time.Now().Format("2006-01-02")
	exec := global2.Live().Exec("update db_top_user b5,(select  b1.uid,b1.day_fans_stat,if(b2.week_fans_stat is null,0,b2.week_fans_stat) week_fans_stat,if(b3.month_fans_stat is null,0,b3.month_fans_stat)month_fans_stat "+
		"from(select uid,sum(num)day_fans_stat from(select t1.uid, if(t2.anchorid is null,0,1)num from db_top_user t1 left join db_anchor_fans t2 on t1.uid=t2.anchorid and t2.create_time>=? where t1.date=?)a "+
		"GROUP BY uid)b1 left join (select uid,count(1) week_fans_stat from db_top_user t1,db_anchor_fans t2 where t1.date=? and t1.uid=t2.anchorid and t2.create_time>=? group by uid)b2 on b1.uid=b2.uid left join (select uid,count(1) "+
		"month_fans_stat from db_top_user t1,db_anchor_fans t2 where t1.date=? and t1.uid=t2.anchorid and t2.create_time>=? group by uid)b3 on b1.uid=b3.uid)b4 set b5.day_fans_stat=b4.day_fans_stat,b5.week_fans_stat=b4.week_fans_stat,"+
		"b5.month_fans_stat=b4.month_fans_stat where b5.uid=b4.uid and b5.date=?", today, today, today, utils.WeekStart().Format("2006-01-02"), today, utils.MonthStart().Format("2006-01-02"), today)
	global2.Log.Debug(fmt.Sprintf("日期为:%s ,同步取消关注的数值%d条", today, exec.RowsAffected))
}

func syncWeekGuessStat() {
	// 竞猜榜

	var winStat []Stat
	var lostStat []Stat
	var cancelStat []struct {
		Amount int64
		Profit int64
		UID    int64
	}
	global2.GetR().Model(&models_guess.GuessOrder{}).Select("uid, sum(profit-amount) as stat").Where("update_time>=? and status=3", utils.WeekStart().Format("2006-01-02")).Group("uid").Scan(&winStat)
	global2.GetR().Model(&models_guess.GuessOrder{}).Select("uid, amount as stat").Where("update_time>=? and status=2", utils.WeekStart().Format("2006-01-02")).Scan(&lostStat)
	global2.GetR().Model(&models_guess.GuessOrder{}).Select("uid, amount as amount, profit").Where("update_time>=? and status=4", utils.WeekStart().Format("2006-01-02")).Scan(&cancelStat)

	//如有取消订单，重建今日数据
	if len(cancelStat) > 0 {
		global2.Live().Model(&models_main.TopUser{}).Where("date=?", time.Now().Format("2006-01-02")).Delete(&models_main.TopUser{})
	}
	for idx, v := range winStat {
		for _, l := range lostStat {
			if v.UID == l.UID {
				winStat[idx].Stat = winStat[idx].Stat - l.Stat
			}
		}
	}

	// 冒泡取前20
	length := len(winStat)
	for i := 0; i < length; i++ {
		for j := 0; j < length-1-i; j++ {
			if winStat[j].Stat < winStat[j+1].Stat {
				winStat[j], winStat[j+1] = winStat[j+1], winStat[j]
			}
		}
	}

	if length >= 20 {
		for i := 0; i < 20; i++ {
			exec := global2.Live().Exec("INSERT INTO db_top_user (uid,updated_at,date,week_guess_stat) value(?,now(),date_format(now(),'%Y-%m-%d'),?)  ON DUPLICATE KEY UPDATE week_guess_stat=?", winStat[i].UID, winStat[i].Stat, winStat[i].Stat)
			global2.Log.Debug(fmt.Sprintf("日期为:%s ,更新当前竞猜为%d条", utils.WeekStart().Format("2006-01-02"), exec.RowsAffected))
		}
	} else {
		for i := 0; i < length; i++ {
			exec := global2.Live().Exec("INSERT INTO db_top_user (uid,updated_at,date,week_guess_stat) value(?,now(),date_format(now(),'%Y-%m-%d'),?)  ON DUPLICATE KEY UPDATE week_guess_stat=?", winStat[i].UID, winStat[i].Stat, winStat[i].Stat)
			global2.Log.Debug(fmt.Sprintf("日期为:%s ,更新当前竞猜为%d条", utils.WeekStart().Format("2006-01-02"), exec.RowsAffected))
		}
	}

	// exec := global.Live().Exec("INSERT INTO db_top_user (uid,updated_at,date,week_guess_stat) select uid ,now(),date_format(now(),'%Y-%m-%d') ,"+
	// 	"sum(profit-amount) as stat from main.db_guess_order where create_time>=? and status=3 group by uid order by stat desc limit 20  ON DUPLICATE KEY UPDATE week_guess_stat=values(week_guess_stat)", util.WeekStart().Format("2006-01-02"))
	// global.Log.Debug(fmt.Sprintf("日期为:%s ,更新当前竞猜为%d条", util.WeekStart().Format("2006-01-02"), exec.RowsAffected))

}
